/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package eu.fastl.dragster.aop;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.fastl.dragster.cache.CacheKey;
import eu.fastl.dragster.cache.CacheKeyFactory;
import eu.fastl.dragster.cache.CacheProvider;

/**
 * Interceptor for caching results of method executions based on the parameters
 *
 * @author Ernst Fastl
 */
public class CachingMethodInterceptor implements MethodInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(CachingMethodInterceptor.class);

    public Object invoke(MethodInvocation invocation) throws Throwable {

        CacheKey key = createCacheKey(invocation);
        Object cachedRetval = CacheProvider.getCache().get(key);
        if (cachedRetval != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Cache Hit for " + key);
            }
            return cachedRetval;
        }
        Object retval = invocation.proceed();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Storing method execution result for " + key);
        }
        CacheProvider.getCache().put(key, retval);
        return retval;
    }

    private CacheKey createCacheKey(MethodInvocation invocation) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Creating cache key for method invocation:" + invocation);
        }
        List<Object> participatingObjects = new ArrayList<Object>();
        participatingObjects.add(invocation.getThis().toString());
        participatingObjects.add(invocation.getMethod().toString());
        Object[] arguments = invocation.getArguments();
        if (arguments.length == 1 && isObjectArray(arguments[0]) ) {
            participatingObjects.addAll(Arrays.asList((Object[]) arguments[0]));
        } else {
            participatingObjects.addAll(Arrays.asList(arguments));
        }

        return CacheKeyFactory.createCacheKey(participatingObjects);
    }

    private static boolean isObjectArray(final Object obj) {
        if (obj != null)
           if(obj.getClass().isArray()){
               return "[Ljava.lang.Object;".equals(obj.getClass().getName());
           }
        return false;
     }

}
